<template>
  <div class="campus-manage">
    <!-- ① 校区管理（与管理员管理格式一致） -->
    <h3 class="section-title">校区管理</h3>
    <el-table :data="campuses" style="width: 100%">
      <el-table-column prop="id" label="校区ID" width="80" />
      <el-table-column prop="name" label="校区名称" />
      <el-table-column prop="address" label="地址" />
      <el-table-column prop="principal" label="负责人" />
      <el-table-column prop="phone" label="电话" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="editCampus(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteCampus(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-button type="primary" class="mt-16" @click="addCampus">新增校区</el-button>

    <!-- ② 管理员管理（与上方格式完全一致） -->
    <h3 class="section-title">管理员管理</h3>
    <el-table :data="admins" style="width: 100%; margin-top: 16px">
      <el-table-column prop="id" label="用户ID" width="80" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="campus_name" label="管理校区" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="editAdmin(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteAdmin(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-button type="primary" class="mt-16" @click="addAdmin">新增管理员</el-button>

    <!-- 共用对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form :model="form" label-width="100px">
        <template v-if="dialogType === 'campus'">
          <el-form-item label="校区名称"><el-input v-model="form.name" /></el-form-item>
          <el-form-item label="地址"><el-input v-model="form.address" /></el-form-item>
          <el-form-item label="电话"><el-input v-model="form.phone" /></el-form-item>
          <el-form-item label="邮箱"><el-input v-model="form.email" /></el-form-item>
        </template>
        <template v-if="dialogType === 'admin'">
          <el-form-item label="用户名"><el-input v-model="form.username" /></el-form-item>
          <el-form-item label="密码"><el-input v-model="form.password" type="password" show-password /></el-form-item>
          <el-form-item label="管理校区">
            <el-select v-model="form.campus_id" placeholder="请选择校区">
              <el-option v-for="c in campusOptions" :key="c.id" :label="c.name" :value="c.id" />
            </el-select>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveDialog">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

/* ---------- 数据 ---------- */
const campuses = ref([])
const admins = ref([])
const campusOptions = ref([])

const dialogVisible = ref(false)
const dialogType = ref('campus')
const dialogTitle = computed(() => (dialogType.value === 'campus' ? '编辑校区' : '新增管理员'))
const form = ref({})
const currentId = ref(null)

/* ---------- 生命周期 ---------- */
onMounted(() => {
  fetchCampuses()
  fetchAdmins()
  fetchCampusOptions()
})

/* ---------- 校区功能 ---------- */
const fetchCampuses = async () => {
  const res = await request.get('/campus/list')
  if (res.code === 200) {
    campuses.value = res.data.map(c => ({ ...c, principal: '' }))
    await Promise.all(campuses.value.map(fetchPrincipal))
  }
}

const fetchPrincipal = async (campus) => {
  const principalRes = await request.get('/user/info', { params: { campusId: campus.id, userType: 'admin' } })
  campus.principal = principalRes.data?.real_name || '未知'
}

const addCampus = () => {
  dialogType.value = 'campus'
  form.value = { name: '', address: '', phone: '', email: '' }
  currentId.value = null
  dialogVisible.value = true
}

const editCampus = (row) => {
  dialogType.value = 'campus'
  form.value = { ...row }
  currentId.value = row.id
  dialogVisible.value = true
}

const saveCampus = async () => {
  if (currentId.value) {
    await request.put(`/campus/update/${currentId.value}`, form.value)
  } else {
    await request.post('/campus/add', form.value)
  }
  ElMessage.success('校区保存成功')
  dialogVisible.value = false
  await fetchCampuses()
}

const deleteCampus = async (id) => {
  await ElMessageBox.confirm('确定删除该校区？', '提示', { type: 'warning' })
  await request.delete(`/campus/delete/${id}`)
  ElMessage.success('校区删除成功')
  await fetchCampuses()
}

/* ---------- 管理员功能 ---------- */
const fetchAdmins = async () => {
  const res = await request.get('/user/admin-list')
  if (res.code === 200) admins.value = res.data
}

const fetchCampusOptions = async () => {
  const res = await request.get('/campus/options')
  if (res.code === 200) campusOptions.value = res.data
}

const addAdmin = () => {
  dialogType.value = 'admin'
  form.value = { username: '', password: '', campus_id: '' }
  currentId.value = null
  dialogVisible.value = true
}

const editAdmin = (row) => {
  dialogType.value = 'admin'
  form.value = { username: row.username, password: '', campus_id: row.campus_id }
  currentId.value = row.id
  dialogVisible.value = true
}

const saveDialog = async () => {
  if (dialogType.value === 'campus') {
    await saveCampus()
  } else {
    if (currentId.value) {
      await request.put(`/user/admin/${currentId.value}`, {
        password: form.value.password,
        campus_id: form.value.campus_id
      })
    } else {
      await request.post('/user/admin', {
        username: form.value.username,
        password: form.value.password,
        campus_id: form.value.campus_id,
        user_type: 'admin'
      })
    }
    ElMessage.success('管理员保存成功')
    dialogVisible.value = false
    await fetchAdmins()
  }
}

const deleteAdmin = async (id) => {
  await ElMessageBox.confirm('确定删除该管理员？', '提示', { type: 'warning' })
  await request.delete(`/user/admin/${id}`)
  ElMessage.success('管理员删除成功')
  await fetchAdmins()
}
</script>

<style scoped>
.campus-manage {
  padding: 24px;
}
.section-title {
  margin: 24px 0 12px;
  font-size: 18px;
  color: var(--el-color-primary);
}
.mt-16 {
  margin-top: 16px;
}
</style>